package com.owen.redis.redisson.consumer.init.task;

import com.owen.redis.redisson.producer.entity.Test;
import org.redisson.api.RQueue;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Objects;

@Component
public class StartTask {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @PostConstruct
    public void startTask() {
        RTopic testMq = redissonClient.getTopic("testMq");
        testMq.addListener(Test.class, (channel, data) -> {
            System.out.println(data);
        });
        threadPoolTaskExecutor.execute(() -> {
            RQueue testQueue = redissonClient.getQueue("testQueue");
            while (true){
                Object poll = testQueue.poll();
                if(Objects.nonNull(poll)){
                    System.out.println(poll);
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        // queue 的 Listener 只能订阅删除哪个队列的消息
//        RQueue testQueue = redissonClient.getQueue("testQueue");
//        Object poll = testQueue.poll();
//        System.out.println(poll);
//        testQueue.addListener((DeletedObjectListener) name -> {
//            System.out.println(name);
//        });
    }

}
